package com.csun.cmny.provider.web.rpc;

import com.csun.cmny.base.dto.LoginAuthDto;
import com.csun.cmny.base.enums.ErrorCodeEnum;
import com.csun.cmny.core.support.BaseController;
import com.csun.cmny.provider.exceptions.OmcBizException;
import com.csun.cmny.provider.model.domain.*;
import com.csun.cmny.provider.model.dto.check_in.CheckInDaysDto;
import com.csun.cmny.provider.model.move.MoveOldmanIeType;
import com.csun.cmny.provider.model.move.MoveOldmanTypeIetype;
import com.csun.cmny.provider.model.move.MovePaymentDerate;
import com.csun.cmny.provider.model.move.MoveUserType;
import com.csun.cmny.provider.model.vo.ExpenseItemVo;
import com.csun.cmny.provider.model.vo.check_in.CheckInDaysVo;
import com.csun.cmny.provider.pojo.Bed;
import com.csun.cmny.provider.pojo.Oldman;
import com.csun.cmny.provider.service.*;
import com.csun.cmny.provider.utils.DateUtil;
import com.csun.cmny.util.wrapper.WrapMapper;
import com.csun.cmny.util.wrapper.Wrapper;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

@RestController
@Transactional
@Slf4j
public class OmcDataMoveFeighClient extends BaseController implements OmcDataMoveFeighApi {

    @Resource
    private OmcUserTypeService omcUserTypeService;
    @Resource
    private OldmanService oldmanService;
    @Resource
    private OmcOldManSupplementService omcOldManSupplementService;
    @Resource
    private OmcExpenseTypeService omcExpenseTypeService;
    @Resource
    private OmcOldManTypeIetypeService omcOldManTypeIetypeService;
    @Resource
    private OmcOldManIetypeStashService omcOldManIetypeStashService;
    @Resource
    private OmcPrepaidCycleService omcPrepaidCycleService;
    @Resource
    private OmcPaymentCycleService omcPaymentCycleService;
    @Resource
    private OmcReturnFeeConfigService omcReturnFeeConfigService;
    @Resource
    private OmcExpenseItemService omcExpenseItemService;
    @Resource
    private OmcOldmanExpenseItemService omcOldmanExpenseItemService;
    @Resource
    private OmcCycleExpenseItemService omcCycleExpenseItemService;
    @Resource
    private OmcOldmanPaidExpenseItemService omcOldmanPaidExpenseItemService;
    @Resource
    private OmcOldManBillService omcOldManBillService;
    @Resource
    private BedService bedService;
    @Resource
    private OmcAdvisoryService omcAdvisoryService;
    @Resource
    private OmcOldManAccountFundsService omcOldManAccountFundsService;

    @Override
    public int moveOldmanTypeToCmny(@RequestBody List<MoveUserType> moveUserTypeList) {

        List<OmcUserType> userTypes = Lists.newArrayList();
//        moveUserTypeList.forEach(m -> {
//            OmcUserType userType = new OmcUserType();
//            BeanUtils.copyProperties(m, userType);
//            userType.setCreator("admin");
//            userType.setCreatorId(1L);
//            userType.setLastOperator("admin");
//            userType.setLastOperatorId(1L);
//            userTypes.add(userType);
//        });
//
//        int ret = omcUserTypeService.batchSave(userTypes);
//
//        log.info("==================== 【添加的人员类别数量】 ： " + ret + "=====================");

        List<OmcUserType> userTypeList = omcUserTypeService.selectAll();

        int count = 0;
        List<OmcOldManSupplement> oldManSupplementList = omcOldManSupplementService.selectAll();

        for (OmcOldManSupplement o : oldManSupplementList) {
            for (OmcUserType u : userTypeList) {
                if (o.getGroupId() != null) {
                    if (o.getGroupId().equals(u.getGroupId()) && o.getPeopleType().toString().equals(u.getUserTypeCode())) {
                        o.setPeopleType(u.getId());
                        count += omcOldManSupplementService.updateById(o);
                    }
                }
            }
        }
        log.info("==================== 【更新老人的人员类别关联数量】 ： " + count + "=====================");

        return 1;
    }

    @Override
    public Wrapper<Integer> movePeopleTypeSubstractRate(@RequestBody List<MoveOldmanTypeIetype> ntOldmanTypeIetypeList) {

        /*
         * 代码生成的减免比例  前端无法解析  关闭代码的自动生成
         * */
/*        //人员类别
        List<OmcUserType> userTypeList = omcUserTypeService.selectAll();

        //减免比例
        List<OmcOldManTypeIetype> oldManTypeIetypeList = Lists.newArrayList();

        //消费类别
        List<OmcExpenseType> expenseTypes = omcExpenseTypeService.selectAll();
        for(MoveOldmanTypeIetype m : ntOldmanTypeIetypeList){
            for(OmcExpenseType e : expenseTypes){
                if(m.getItemid().equals(e.getVersion()) && m.getHomeid().toString().equals(e.getGroupId().toString())){
                    OmcOldManTypeIetype oldManTypeIetype = new OmcOldManTypeIetype();
                    //写入数据
                    oldManTypeIetype.setItemId(e.getId());
                    oldManTypeIetype.setGroupId(e.getGroupId());
                    oldManTypeIetype.setPrecent((int)(m.getPrecent()*100));
                    oldManTypeIetype.setRemark(m.getRemark());
                    oldManTypeIetype.setCreator("admin");
                    oldManTypeIetype.setCreatorId(1L);
                    oldManTypeIetype.setLastOperatorId(m.getModifier());
                    oldManTypeIetype.setLastOperator("admin");
                    for(OmcUserType u : userTypeList){
                        if(m.getOldmantypeid().toString().equals(u.getUserTypeCode()) && m.getHomeid().toString().equals(u.getGroupId().toString())){
                            oldManTypeIetype.setUserTypeId(u.getId());
                            break;
                        }
                    }
                    oldManTypeIetypeList.add(oldManTypeIetype);
                }
                if(e.getVersion().equals(0)){
                    OmcOldManTypeIetype oldManTypeIetype = new OmcOldManTypeIetype();
                    //写入数据
                    oldManTypeIetype.setItemId(e.getId());
                    oldManTypeIetype.setGroupId(e.getGroupId());
                    oldManTypeIetype.setPrecent(0);
                    oldManTypeIetype.setRemark(m.getRemark());
                    oldManTypeIetype.setCreator("admin");
                    oldManTypeIetype.setCreatorId(1L);
                    oldManTypeIetype.setLastOperatorId(m.getModifier());
                    oldManTypeIetype.setLastOperator("admin");
                    for(OmcUserType u : userTypeList){
                        if(m.getOldmantypeid().toString().equals(u.getUserTypeCode()) && m.getHomeid().toString().equals(u.getGroupId().toString())){
                            oldManTypeIetype.setUserTypeId(u.getId());
                            break;
                        }
                    }
                    oldManTypeIetypeList.add(oldManTypeIetype);
                }
            }
        }
        int ret = omcOldManTypeIetypeService.batchSave(oldManTypeIetypeList);

        log.info("==================== 【添加减免比例的数量】 ： " + oldManTypeIetypeList.size() + " =====================");
*/
        int count = 0;

        LoginAuthDto loginAuthDto = new LoginAuthDto();
        loginAuthDto.setUserId(1L);
        loginAuthDto.setUserName("admin");
        loginAuthDto.setLoginName("admin");
        loginAuthDto.setGroupName("admin");

        List<OmcOldManSupplement> oldManSupplementList = omcOldManSupplementService.selectAll();
        for (OmcOldManSupplement o : oldManSupplementList) {
            OmcOldManIetypeStash dto = new OmcOldManIetypeStash();
            dto.setOldManId(o.getOldManId());
            dto.setUserTypeId(o.getPeopleType());
            loginAuthDto.setGroupId(o.getGroupId());
            int ret = omcOldManIetypeStashService.moveIetypeStash(dto, loginAuthDto);
            count++;
        }

        log.info("==================== 【添加老人暂存比例的数量】 ： " + count + "=====================");

        return WrapMapper.ok(count);
    }

    @Override
    public Wrapper<Integer> initExpenseConfig(@RequestParam("groupIdList") List<Long> groupIdList) {

        List<OmcPrepaidCycle> prepaidCycleList = Lists.newArrayList();

        List<OmcPaymentCycle> cycleList = Lists.newArrayList();

        List<OmcReturnFeeConfig> returnFeeConfigList = Lists.newArrayList();

        String cron = "00 00 00 01 1-12 ? *";

        //计费配置
        for (Long groupId : groupIdList) {

            //预缴周期
            OmcPrepaidCycle prepaidCycle0 = new OmcPrepaidCycle();
            prepaidCycle0.setIsAddSurplusDays(1);
            prepaidCycle0.setPrepaidMonthNum(0);
            prepaidCycle0.setGroupId(groupId);
            prepaidCycle0.setCreator("admin");
            prepaidCycle0.setCreatorId(1L);
            prepaidCycle0.setLastOperator("admin");
            prepaidCycle0.setLastOperatorId(1L);
            prepaidCycleList.add(prepaidCycle0);

            OmcPrepaidCycle prepaidCycle1 = new OmcPrepaidCycle();
            prepaidCycle1.setIsAddSurplusDays(1);
            prepaidCycle1.setPrepaidMonthNum(1);
            prepaidCycle1.setGroupId(groupId);
            prepaidCycle1.setCreator("admin");
            prepaidCycle1.setCreatorId(1L);
            prepaidCycle1.setLastOperator("admin");
            prepaidCycle1.setLastOperatorId(1L);
            prepaidCycleList.add(prepaidCycle1);

            OmcPrepaidCycle prepaidCycle3 = new OmcPrepaidCycle();
            prepaidCycle3.setIsAddSurplusDays(1);
            prepaidCycle3.setPrepaidMonthNum(3);
            prepaidCycle3.setGroupId(groupId);
            prepaidCycle3.setCreator("admin");
            prepaidCycle3.setCreatorId(1L);
            prepaidCycle3.setLastOperator("admin");
            prepaidCycle3.setLastOperatorId(1L);
            prepaidCycleList.add(prepaidCycle3);

            OmcPrepaidCycle prepaidCycle6 = new OmcPrepaidCycle();
            prepaidCycle6.setIsAddSurplusDays(1);
            prepaidCycle6.setPrepaidMonthNum(6);
            prepaidCycle6.setGroupId(groupId);
            prepaidCycle6.setCreator("admin");
            prepaidCycle6.setCreatorId(1L);
            prepaidCycle6.setLastOperator("admin");
            prepaidCycle6.setLastOperatorId(1L);
            prepaidCycleList.add(prepaidCycle6);

            OmcPrepaidCycle prepaidCycle12 = new OmcPrepaidCycle();
            prepaidCycle12.setIsAddSurplusDays(1);
            prepaidCycle12.setPrepaidMonthNum(12);
            prepaidCycle12.setGroupId(groupId);
            prepaidCycle12.setCreator("admin");
            prepaidCycle12.setCreatorId(1L);
            prepaidCycle12.setLastOperator("admin");
            prepaidCycle12.setLastOperatorId(1L);
            prepaidCycleList.add(prepaidCycle12);

            //账单生成周期
            OmcPaymentCycle cycle = new OmcPaymentCycle();
            cycle.setPaymentRecordGenerateConfig(cron);
            cycle.setGroupId(groupId);
            cycle.setCreator("admin");
            cycle.setCreatorId(1L);
            cycle.setLastOperator("admin");
            cycle.setLastOperatorId(1L);
            cycleList.add(cycle);

            //退费天数设置
            OmcReturnFeeConfig returnFeeConfig = new OmcReturnFeeConfig();
            returnFeeConfig.setGroupId(groupId);
            returnFeeConfig.setCycleMaxDays(0);
            returnFeeConfig.setReturnFeeDays(0);
            returnFeeConfig.setTakeOffDays(0);
            returnFeeConfig.setCycleTotalDays(30);
            returnFeeConfig.setIsZero(1);
            returnFeeConfig.setCreator("admin");
            returnFeeConfig.setCreatorId(1L);
            returnFeeConfig.setLastOperator("admin");
            returnFeeConfig.setLastOperatorId(1L);
            returnFeeConfigList.add(returnFeeConfig);
        }

        int retPrepadiCycle = omcPrepaidCycleService.batchSave(prepaidCycleList);
        int retPaymentCycle = omcPaymentCycleService.batchSave(cycleList);
        int retReturnFeeConfig = omcReturnFeeConfigService.batchSave(returnFeeConfigList);

        log.info("==================== 【添加预缴周期数量】 ： " + retPrepadiCycle + " =====================");
        log.info("==================== 【添加账单生成周期数量】 ： " + retPaymentCycle + " =====================");
        log.info("==================== 【添加退费天数配置数量】 ： " + retReturnFeeConfig + " =====================");

        return WrapMapper.ok(retPrepadiCycle + retPaymentCycle + retReturnFeeConfig);
    }

    @Override
    public Wrapper<Integer> moveOldmanIn(@RequestBody MoveOldmanIeType oldmanIeType) {

        //查询机构的消费项目
        OmcExpenseItem itemQuery = new OmcExpenseItem();
        itemQuery.setGroupId(oldmanIeType.getGroupId());
        List<OmcExpenseItem> itemList = omcExpenseItemService.select(itemQuery);

        //定义老人id
        Long oldmanId = oldmanIeType.getOldManId().longValue();

        //生成减免
        HashMap<String, MovePaymentDerate> manualMap = new HashMap<>();
        oldmanIeType.getManualList().forEach(n -> {
            manualMap.put(n.getIetypeName(), n);
        });

        List<OmcOldmanExpenseItem> oldmanExpenseItemList = Lists.newArrayList();

        if(oldmanIeType != null && oldmanIeType.getBedId() != null){
            OmcOldManSupplement oldManSupplement = new OmcOldManSupplement();
            oldManSupplement.setOldManId(oldmanIeType.getOldManId().longValue());
            oldManSupplement = omcOldManSupplementService.selectOne(oldManSupplement);
            oldManSupplement.setBedId(oldmanIeType.getBedId().longValue());
            int o = omcOldManSupplementService.update(oldManSupplement);

            //匹配床位费
            LoginAuthDto loginAuthDto = new LoginAuthDto();
            loginAuthDto.setGroupId(oldmanIeType.getGroupId());
            OmcExpenseItem expenseItemQuery = omcOldmanExpenseItemService.mathcBedFeeByBedId(oldmanIeType.getBedId().longValue(), loginAuthDto);
            OmcOldmanExpenseItem item = new OmcOldmanExpenseItem();
            item.setOldmanId(oldmanId);
            item.setExpenseTypeId(expenseItemQuery.getExpenseTypeId().longValue());
            item.setModelCode(2);
            item.setStatus(1);
            item.setAmount(1);
            if(manualMap.get("床位费") != null && manualMap.get("床位费").getDerateFee() != null){
                item.setChargeStandard(manualMap.get("床位费").getDerateFee());
            }else{
                item.setChargeStandard(BigDecimal.ZERO);
            }
            item.setExpenseItemId(expenseItemQuery.getId());
            oldmanExpenseItemList.add(item);
        }

        for(OmcExpenseItem i : itemList){
            //组装数据
            //基础护理费 nLevelFee
            String itemName = i.getItemName();
            BigDecimal itemFee = i.getChargeStandard();
            String nLevelFee = oldmanIeType.getNLevelName();
            BigDecimal nLevel = oldmanIeType.getNLevelActFee();
            if (oldmanIeType.getNLevelActFee() != null) {
                if(oldmanIeType.getNLevelName().equals(i.getItemName())){
                    if(i.getItemName().equals("自理") && i.getChargeStandard().compareTo(BigDecimal.ZERO) == 0){
                        OmcOldmanExpenseItem item = new OmcOldmanExpenseItem();
                        item.setOldmanId(oldmanId);
                        item.setExpenseTypeId(i.getExpenseTypeId().longValue());
                        item.setModelCode(2);
                        item.setStatus(1);
                        item.setAmount(1);
                        if(manualMap.get("基础护理费") != null && manualMap.get("基础护理费").getDerateFee() != null){
                            item.setChargeStandard(manualMap.get("基础护理费").getDerateFee());
                        }else{
                            item.setChargeStandard(BigDecimal.ZERO);
                        }
                        item.setExpenseItemId(i.getId());
                        oldmanExpenseItemList.add(item);
                    }
                    if(!i.getItemName().equals("自理")){
                        OmcOldmanExpenseItem item = new OmcOldmanExpenseItem();
                        item.setOldmanId(oldmanId);
                        item.setExpenseTypeId(i.getExpenseTypeId().longValue());
                        item.setModelCode(2);
                        item.setStatus(1);
                        item.setAmount(1);
                        if(manualMap.get("基础护理费") != null && manualMap.get("基础护理费").getDerateFee() != null){
                            item.setChargeStandard(manualMap.get("基础护理费").getDerateFee());
                        }else{
                            item.setChargeStandard(BigDecimal.ZERO);
                        }
                        item.setExpenseItemId(i.getId());
                        oldmanExpenseItemList.add(item);
                    }
                }
            }
            //私人定制项目费用 privateFee
            if(oldmanIeType.getPrivateItemNameList().size() > 0){
                List<String> privateItemNameList = oldmanIeType.getPrivateItemNameList();
                if(privateItemNameList.size() > 0){
                    for(String privateItemName : privateItemNameList){
                        if(privateItemName != null && privateItemName.equals(i.getItemName())){
                            OmcOldmanExpenseItem item = new OmcOldmanExpenseItem();
                            item.setOldmanId(oldmanId);
                            item.setExpenseTypeId(i.getExpenseTypeId().longValue());
                            item.setModelCode(2);
                            item.setStatus(1);
                            item.setAmount(1);
//                            item.setChargeStandard(i.getChargeStandard());
                            item.setExpenseItemId(i.getId());
                            if(manualMap.get("单项定制服务费") != null && manualMap.get("单项定制服务费").getDerateFee() != null){
                                if(manualMap.get("单项定制服务费").getDerateFee().compareTo(BigDecimal.ZERO) == 0){
                                    item.setChargeStandard(BigDecimal.ZERO);
                                }else{
                                    item.setChargeStandard(manualMap.get("单项定制服务费").getDerateFee().divide(new BigDecimal(privateItemNameList.size())));
                                }
                            }else{
                                item.setChargeStandard(BigDecimal.ZERO);
                            }
                            oldmanExpenseItemList.add(item);
                        }
                    }
                }
            }
            //床位费 bedFee
       /*     String itemName2 = i.getItemName();
            BigDecimal itemFee2 = i.getChargeStandard();
            String getMealName = oldmanIeType.getBedInstruction();
            BigDecimal getMealActFee = oldmanIeType.getBedActFee();
            if(oldmanIeType.getBedActFee() != null && oldmanIeType.getBedActFee().compareTo(i.getChargeStandard()) == 0 && oldmanIeType.getBedInstruction() !=null && oldmanIeType.getBedInstruction().equals(i.getContent())){
                OmcOldmanExpenseItem item = new OmcOldmanExpenseItem();
                item.setOldmanId(oldmanId);
                item.setExpenseTypeId(i.getExpenseTypeId().longValue());
                item.setModelCode(2);
                item.setStatus(1);
                item.setAmount(1);
//                item.setChargeStandard(i.getChargeStandard());
                item.setExpenseItemId(i.getId());
                if(manualMap.get("床位费") != null && manualMap.get("床位费").getDerateFee() != null){
                    item.setChargeStandard(manualMap.get("床位费").getDerateFee());
                }else{
                    item.setChargeStandard(BigDecimal.ZERO);
                }
                item.setExpenseItemId(i.getId());
                oldmanExpenseItemList.add(item);
            }*/
            String itemName3 = i.getItemName();
            BigDecimal itemFee3 = i.getChargeStandard();
            String getMealName3 = oldmanIeType.getMealName();
            BigDecimal getMealActFee3 = oldmanIeType.getMealActFee();
            //伙食费 mealFee
            if(oldmanIeType.getMealName() != null && oldmanIeType.getMealName().equals(i.getItemName())){
                OmcOldmanExpenseItem item = new OmcOldmanExpenseItem();
                item.setOldmanId(oldmanId);
                item.setExpenseTypeId(i.getExpenseTypeId().longValue());
                item.setModelCode(2);
                item.setStatus(1);
                item.setAmount(1);
                item.setExpenseItemId(i.getId());
                if(manualMap.get("餐饮费") != null && manualMap.get("餐饮费").getDerateFee() != null){
                    item.setChargeStandard(manualMap.get("餐饮费").getDerateFee());
                }else{
                    item.setChargeStandard(BigDecimal.ZERO);
                }
                item.setExpenseItemId(i.getId());
                oldmanExpenseItemList.add(item);
            }
            if(oldmanIeType.getDisActFee() != null && oldmanIeType.getDisActFee().compareTo(i.getChargeStandard()) == 0 && i.getItemName() != null && i.getItemName().equals("自理")){
                OmcExpenseType t = omcExpenseTypeService.selectByKey(i.getExpenseTypeId().longValue());
                if(t.getName().equals("一次性费用")){
                    OmcOldmanExpenseItem item = new OmcOldmanExpenseItem();
                    item.setOldmanId(oldmanId);
                    item.setExpenseTypeId(i.getExpenseTypeId().longValue());
                    item.setModelCode(1);
                    item.setStatus(1);
                    item.setAmount(1);
                    if(manualMap.get("一次性费用") != null && manualMap.get("一次性费用").getDerateFee() != null){
                        item.setChargeStandard(manualMap.get("一次性费用").getDerateFee());
                    }else{
                        item.setChargeStandard(BigDecimal.ZERO);
                    }
                    item.setExpenseItemId(i.getId());
                    oldmanExpenseItemList.add(item);
                }
            }
//            if(oldmanIeType.getDisActFee() != null && oldmanIeType.getDisActFee().compareTo(i.getChargeStandard()) == 0 && i.getItemName().equals("自理")){
//                OmcExpenseType t = omcExpenseTypeService.selectByKey(i.getExpenseTypeId().longValue());
//                if(t.getName().equals("一次性费用")){
//                    OmcOldmanExpenseItem item = new OmcOldmanExpenseItem();
//                    item.setOldmanId(oldmanId);
//                    item.setExpenseTypeId(i.getExpenseTypeId().longValue());
//                    item.setModelCode(1);
//                    item.setStatus(1);
//                    item.setAmount(1);
//                    if(manualMap.get("一次性费用").getDerateFee() != null){
//                        item.setChargeStandard(manualMap.get("一次性费用").getDerateFee());
//                    }else{
//                        item.setChargeStandard(BigDecimal.ZERO);
//                    }
//                    item.setExpenseItemId(i.getId());
//                    oldmanExpenseItemList.add(item);
//                }
//            }
            String itemName4 = i.getItemName();
            BigDecimal itemFee4 = i.getChargeStandard();
            BigDecimal disActFee2 = oldmanIeType.getDisActFee();
            if(oldmanIeType.getDisActFee() != null && oldmanIeType.getDisActFee().compareTo(i.getChargeStandard()) == 0 && i.getItemName().equals("介护")){
                OmcExpenseType t = omcExpenseTypeService.selectByKey(i.getExpenseTypeId().longValue());
                if(t.getName().equals("一次性费用")){
                    OmcOldmanExpenseItem item = new OmcOldmanExpenseItem();
                    item.setOldmanId(oldmanId);
                    item.setExpenseTypeId(i.getExpenseTypeId().longValue());
                    item.setModelCode(1);
                    item.setStatus(1);
                    item.setAmount(1);
                    if(manualMap.get("一次性费用") != null && manualMap.get("一次性费用").getDerateFee() != null){
                        item.setChargeStandard(manualMap.get("一次性费用").getDerateFee());
                    }else{
                        item.setChargeStandard(BigDecimal.ZERO);
                    }
                    item.setExpenseItemId(i.getId());
                    oldmanExpenseItemList.add(item);
                }
            }
            if(oldmanIeType.getDisActFee() != null && oldmanIeType.getDisActFee().compareTo(new BigDecimal(230)) == 0) {
                if (i.getItemName().equals("介护")) {
                    OmcOldmanExpenseItem item = new OmcOldmanExpenseItem();
                    item.setOldmanId(oldmanId);
                    item.setExpenseTypeId(i.getExpenseTypeId().longValue());
                    item.setModelCode(1);
                    item.setStatus(1);
                    item.setAmount(1);
                    if(manualMap.get("一次性费用") != null && manualMap.get("一次性费用").getDerateFee() != null){
                        item.setChargeStandard(manualMap.get("一次性费用").getDerateFee().divide(new BigDecimal(2)));
                    }else{
                        item.setChargeStandard(BigDecimal.ZERO);
                    }
                    item.setExpenseItemId(i.getId());
                    oldmanExpenseItemList.add(item);
                }
                if (i.getItemName().equals("自理") && i.getChargeStandard().compareTo(new BigDecimal(100)) == 0) {
                    OmcOldmanExpenseItem item = new OmcOldmanExpenseItem();
                    item.setOldmanId(oldmanId);
                    item.setExpenseTypeId(i.getExpenseTypeId().longValue());
                    item.setModelCode(1);
                    item.setStatus(1);
                    item.setAmount(1);
                    if(manualMap.get("一次性费用") != null && manualMap.get("一次性费用").getDerateFee() != null){
                        item.setChargeStandard(manualMap.get("一次性费用").getDerateFee().divide(new BigDecimal(2)));
                    }else{
                        item.setChargeStandard(BigDecimal.ZERO);
                    }
                    item.setExpenseItemId(i.getId());
                    oldmanExpenseItemList.add(item);
                }
            }
        }
        if(oldmanExpenseItemList.size() > 0){
            for(OmcExpenseItem item : itemList){
                if (item.getItemName().equals("入住押金")) {
                    OmcOldmanExpenseItem expenseItem = new OmcOldmanExpenseItem();
                    expenseItem.setOldmanId(oldmanId);
                    expenseItem.setExpenseTypeId(item.getExpenseTypeId().longValue());
                    expenseItem.setModelCode(1);
                    expenseItem.setStatus(1);
                    expenseItem.setAmount(1);
                    if(manualMap.get("入住押金") != null && manualMap.get("入住押金").getDerateFee() != null){
                        expenseItem.setChargeStandard(manualMap.get("入住押金").getDerateFee());
                    }else{
                        expenseItem.setChargeStandard(BigDecimal.ZERO);
                    }
                    expenseItem.setExpenseItemId(item.getId());
                    oldmanExpenseItemList.add(expenseItem);
                }
                if (item.getItemName().equals("公共服务")) {
                    OmcOldmanExpenseItem expenseItem = new OmcOldmanExpenseItem();
                    expenseItem.setOldmanId(oldmanId);
                    expenseItem.setExpenseTypeId(item.getExpenseTypeId().longValue());
                    expenseItem.setModelCode(1);
                    expenseItem.setStatus(1);
                    expenseItem.setAmount(1);
                    if(manualMap.get("公共服务费") != null && manualMap.get("公共服务费").getDerateFee() != null){
                        expenseItem.setChargeStandard(manualMap.get("公共服务费").getDerateFee());
                    }else{
                        expenseItem.setChargeStandard(BigDecimal.ZERO);
                    }
                    expenseItem.setExpenseItemId(item.getId());
                    oldmanExpenseItemList.add(expenseItem);
                }
                if (item.getItemName().equals("周期电费")) {
                    OmcOldmanExpenseItem expenseItem = new OmcOldmanExpenseItem();
                    expenseItem.setOldmanId(oldmanId);
                    expenseItem.setExpenseTypeId(item.getExpenseTypeId().longValue());
                    expenseItem.setModelCode(2);
                    expenseItem.setStatus(1);
                    expenseItem.setAmount(1);
                    expenseItem.setChargeStandard(BigDecimal.ZERO);
                    expenseItem.setExpenseItemId(item.getId());
                    oldmanExpenseItemList.add(expenseItem);
                }
            }
            omcOldmanExpenseItemService.batchSave(oldmanExpenseItemList);
        }
        return  WrapMapper.ok(1);
    }

    @Override
    public Wrapper<Integer> moveOldmanInItem(@RequestBody MoveOldmanIeType oldmanIeType) {
        LoginAuthDto loginAuthDto = new LoginAuthDto();
        loginAuthDto.setLoginName("admin");
        loginAuthDto.setUserName("admin");
        loginAuthDto.setUserId(1L);
        loginAuthDto.setGroupId(oldmanIeType.getGroupId());

        Long oldmanId = oldmanIeType.getOldManId().longValue();


        //查询老人选择的项目
        List<ExpenseItemVo> expenseItemVoList = omcOldmanExpenseItemService.moveQueryOldmanExpenseItem(oldmanId, loginAuthDto);
        if(expenseItemVoList == null || expenseItemVoList.size()<1){
            OmcOldmanExpenseItem delete = new OmcOldmanExpenseItem();
            delete.setOldmanId(oldmanId);
            omcOldmanExpenseItemService.delete(delete);

            OmcOldManSupplement omcOldManSupplement = new OmcOldManSupplement();
            omcOldManSupplement.setOldManId(oldmanId);
            if(omcOldManSupplement != null){
                omcOldManSupplement = omcOldManSupplementService.selectOne(omcOldManSupplement);
                omcOldManSupplement.setIsPayed(0);
                omcOldManSupplementService.update(omcOldManSupplement);
            }

            Oldman oldman = new Oldman();
            oldman.setOldmanId(oldmanId.intValue());
            oldman = oldmanService.selectByOld(oldman);
            if(oldman != null){
                oldman.setStatus(11);
                oldmanService.updateByOldId(oldman);
            }
            return WrapMapper.ok(0);
        }

        OmcOldmanExpenseItem itemQuery = new OmcOldmanExpenseItem();
        itemQuery.setOldmanId(oldmanId);
        List<OmcOldmanExpenseItem> oldmanPaidExpenseItemList = omcOldmanExpenseItemService.select(itemQuery);

        //周期预缴费用
        BigDecimal cycleTotalFee = BigDecimal.ZERO;

        //非周期预缴费用
        BigDecimal unCycleTotalFee = BigDecimal.ZERO;

        //入院实际费用
        BigDecimal inActualFee = BigDecimal.ZERO;

        //周期人工减免费用
        BigDecimal manualSubFeeCycle = BigDecimal.ZERO;

        //周期人员减免费用
        BigDecimal userRateSubFeeCycle = BigDecimal.ZERO;

        //周期总费用
        BigDecimal totalFeeCycle = BigDecimal.ZERO;

        //入院项目人工减免费用
        BigDecimal manualSubFee = BigDecimal.ZERO;

        //入院项目人员减免费用
        BigDecimal userRateSubFee = BigDecimal.ZERO;

        //入院项目总费用
        BigDecimal totalFee = BigDecimal.ZERO;

        //周期缴费项目集合
        List<OmcCycleExpenseItem> cycleItemList = new LinkedList<>();

        //根据预缴周期id获取预缴配置
        OmcPrepaidCycle omcPrepaidCycle = new OmcPrepaidCycle();
        omcPrepaidCycle.setIsAddSurplusDays(1);
        if(oldmanIeType.getPriPaidCycle() != null){
            omcPrepaidCycle.setPrepaidMonthNum(oldmanIeType.getPriPaidCycle());
        }else{
            omcPrepaidCycle.setPrepaidMonthNum(0);
        }
        omcPrepaidCycle.setGroupId(oldmanIeType.getGroupId());
        omcPrepaidCycle = omcPrepaidCycleService.selectOne(omcPrepaidCycle);

        //计算预缴周期月数
        BigDecimal prepaidCycleNum = new BigDecimal(omcPrepaidCycle.getPrepaidMonthNum());

        //获取是否需要预缴该月剩余天数
        int isAddSurplusDays = omcPrepaidCycle.getIsAddSurplusDays();

        //计算剩余天数是多少个周期
        CheckInDaysDto checkInDaysDto = new CheckInDaysDto();
        checkInDaysDto.setGroupId(loginAuthDto.getGroupId());
        checkInDaysDto.setCheckInDate(DateUtil.getDateByString(oldmanIeType.getInDate()));
        CheckInDaysVo checkInDaysVo = omcReturnFeeConfigService.queryCheckInDaysVo(checkInDaysDto);

        //当月剩余周期数
        BigDecimal prepaidSurplus = checkInDaysVo.getPayPercent();

        //当月剩余周期数费用
        BigDecimal surplusCycleFee = BigDecimal.ZERO;

        //实际预缴周期数
        BigDecimal actualPrepaidCycleNum;

        //用户是否选择预缴本月剩余周期
        if(isAddSurplusDays == 1){
            actualPrepaidCycleNum = prepaidSurplus.add(prepaidCycleNum);
        }else{
            actualPrepaidCycleNum = prepaidCycleNum;
        }

        log.info("预缴周期数 : [" + actualPrepaidCycleNum + "]" + "当月剩余周期数 : [" + prepaidSurplus + "]");

        List<OmcOldmanPaidExpenseItem> omcOldmanPaidExpenseItemList = Lists.newArrayList();
        for(OmcOldmanExpenseItem o : oldmanPaidExpenseItemList){
            OmcOldmanPaidExpenseItem i = new OmcOldmanPaidExpenseItem();
            i.setExpenseItemId(o.getExpenseItemId());
            i.setUserRateRefief(o.getChargeStandard());
            omcOldmanPaidExpenseItemList.add(i);
        }

        //循环拷贝数据
        for (ExpenseItemVo vo : expenseItemVoList) {
            for(OmcOldmanPaidExpenseItem omc : omcOldmanPaidExpenseItemList){
                if(vo.getId().equals(omc.getExpenseItemId())){

                    //计算项目实际价格
                    BigDecimal actualFee = vo.getChargeStandard().subtract(vo.getUserTypeRateRefief().add(omc.getUserRateRefief()));

                    //拷贝数据
                    omc.setCode(vo.getCode());
                    omc.setExpenseTypeId(vo.getExpenseTypeId().longValue());
                    omc.setExpenseItemId(vo.getId());
                    omc.setActualFee(actualFee);
                    omc.setAmount(vo.getAmount());
                    omc.setOldmanId(oldmanId);
                    omc.setCostType(vo.getCostType());
                    omc.setGroupId(loginAuthDto.getGroupId());
                    omc.setItemFee(vo.getChargeStandard());
                    omc.setItemName(vo.getItemName());
                    omc.setItemType(vo.getExpenseTypeName());
                    omc.setUserTypeRateRefief(vo.getUserTypeRateRefief());
                    omc.setModelCode(vo.getModelCode());
                    omc.setUpdateInfo(loginAuthDto);
                    omc.setIsAdjust(vo.getIsAdjust());
                    omc.setIsLeaveReturn(vo.getIsLeaveReturn());
                    omc.setIsOutReturn(vo.getIsOutReturn());
                    omc.setIsFixedPrice(vo.getIsFixedPrice());

                    log.info("消费项目 :" + omc.getItemName() + "[ 原价 " + vo.getChargeStandard() + "人员类别减免 " + vo.getUserTypeRateRefief() + "人工减免 " + vo.getUserRateRefief() + " 实际费用 " + actualFee + "]");

                    //周期缴费项目  加入周期总费用
                    if(vo.getModelCode().equals(2)){
                        cycleTotalFee = cycleTotalFee.add(actualFee);
                        surplusCycleFee = surplusCycleFee.add(actualFee);
                        omc.setUsedDegree(prepaidSurplus);
                        omc.setResidueDegree(actualPrepaidCycleNum.subtract(prepaidSurplus));
                        //总费用累加
                        totalFeeCycle = totalFeeCycle.add(vo.getChargeStandard());
                        //人员减免费用累加
                        userRateSubFeeCycle = userRateSubFeeCycle.add(vo.getUserTypeRateRefief());
                        //人工减免费用累加
                        manualSubFeeCycle = manualSubFeeCycle.add(omc.getUserRateRefief());
                        //周期项目写入周期项目表
                        OmcCycleExpenseItem item = new OmcCycleExpenseItem();
                        item.setExpenseTypeId(vo.getExpenseTypeId().longValue());
                        BeanUtils.copyProperties(omc,item);
                        item.setCode(vo.getCode());
                        cycleItemList.add(item);
                    }
                    //将入院缴费项目累加
                    if(vo.getModelCode().equals(1)){
                        inActualFee = inActualFee.add(actualFee.multiply(new BigDecimal(vo.getAmount())));
                        omc.setUsedDegree(BigDecimal.ZERO);
                        omc.setResidueDegree(BigDecimal.ONE);
                        //总费用累加
                        totalFee = totalFee.add(vo.getChargeStandard());
                        //人员减免费用累加
                        userRateSubFee = userRateSubFee.add(vo.getUserTypeRateRefief());
                        //人工减免费用累加
                        manualSubFee = manualSubFee.add(omc.getUserRateRefief());
                    }
                    //将非周期缴费项目累加
                    if(vo.getModelCode().equals(4)){
                        BigDecimal amount = new BigDecimal(vo.getAmount());
                        unCycleTotalFee = unCycleTotalFee.add(actualFee.multiply(amount));
//                        accountSurplusFee = accountSurplusFee.add(actualFee.multiply(amount));
                        omc.setUsedDegree(BigDecimal.ZERO);
                        omc.setResidueDegree(amount);
                    }
                }
            }
        }

        //[周期费用乘以预缴周期数] 预缴费用
        cycleTotalFee = actualPrepaidCycleNum.multiply(cycleTotalFee).setScale(2,BigDecimal.ROUND_HALF_UP);

        totalFeeCycle = actualPrepaidCycleNum.multiply(totalFeeCycle).setScale(2,BigDecimal.ROUND_HALF_UP);
        //人员减免费用累加
        userRateSubFeeCycle = actualPrepaidCycleNum.multiply(userRateSubFeeCycle).setScale(2,BigDecimal.ROUND_HALF_UP);
        //人工减免费用累加
        manualSubFeeCycle = actualPrepaidCycleNum.multiply(manualSubFeeCycle).setScale(2,BigDecimal.ROUND_HALF_UP);


        //预缴费用 = 周期预缴 + 费周期预缴
        BigDecimal totalPrepaidFee = cycleTotalFee.add(unCycleTotalFee);

        //入院缴费 = 入院项目费用 + 预缴费用
        inActualFee = inActualFee.add(totalPrepaidFee).setScale(2,BigDecimal.ROUND_HALF_UP);

        log.info("预缴费用 [ 后端计算结果 : " + totalPrepaidFee + " 历史计算结果 : " + oldmanIeType.getPriPaidFee() + "]" );
        log.info("入院缴费 [ 后端计算结果 : " + inActualFee + " 前端计算结果 : " + oldmanIeType.getActTotalFee());
        log.info("预缴周期数 : [" + actualPrepaidCycleNum + "]" + " 本月剩余周期数 : [" + prepaidSurplus + "]");

        //保存周期缴费项目 保存之前将原有数据删除
        int retCycle = omcCycleExpenseItemService.batchSaveCycleExpenseItem(cycleItemList);

        //保存缴费项目明细 保存之前将原有数据删除
        int retIn = omcOldmanPaidExpenseItemService.batchSaveOldmanPaidExpenseItem(omcOldmanPaidExpenseItemList);

        //生成入院账单
        //1.生成缴费单基本信息
        OmcOldManBill oldManBill = new OmcOldManBill();
        oldManBill.setOldManId(oldmanId);
        oldManBill.setTotalPay(inActualFee);

        OmcOldManSupplement oldManSupplement = new OmcOldManSupplement();
        oldManSupplement.setOldManId(oldmanId);
        oldManSupplement = omcOldManSupplementService.selectOne(oldManSupplement);

        //修改老人状态 已入住
        Oldman oldmanQuery = new Oldman();
        oldmanQuery.setOldmanId(oldmanId.intValue());
        oldmanQuery = oldmanService.selectByOld(oldmanQuery);
        oldmanQuery.setStatus(3);

        //修改老人信息
        int updateRet = oldmanService.updateByOldId(oldmanQuery);

        //2.生成缴费单项目明细
        List<OmcBillItem> billItemList = new LinkedList<>();
        for(OmcOldmanPaidExpenseItem omc : omcOldmanPaidExpenseItemList){
            OmcBillItem item = new OmcBillItem();
            BeanUtils.copyProperties(omc,item);
            item.setId(null);
            billItemList.add(item);
        }

        //4.生成缴费单费用明细
        OmcBillInHospitalFee billInHospitalFee = new OmcBillInHospitalFee();
        billInHospitalFee.setActualFee(inActualFee);
//        billInHospitalFee.setUserRateRefief(manualSubFee.add(manualSubFeeCycle));
//        billInHospitalFee.setUserTypeRateRefief(userRateSubFee.add(userRateSubFeeCycle));
        billInHospitalFee.setTotalFee(totalFeeCycle.add(totalFee));
        billInHospitalFee.setLastMonthFee(totalPrepaidFee);

        OmcBillMeal omcBillMeal = new OmcBillMeal();

        //5.生成入院缴费单
        int result = omcOldManBillService.moveInHospitalBill(oldManBill,billItemList,omcBillMeal,billInHospitalFee,loginAuthDto);

        //6.改变床位状态
        //查询选择的床位Id

        if(oldManSupplement != null){
           /* //校验床位状态
            //如果之前该老人生成缴费单绑定了床位号，先把原来的绑定取消
            Bed bedQuery = new Bed();
            bedQuery.setOldmanId(oldmanId.intValue());
            bedQuery = bedService.selectByBed(bedQuery);
            if(bedQuery != null){
                bedQuery.setOldmanId(null);
                bedQuery.setStatus(0);
                int bedUpdate = bedService.updateBedOldmanIdAndStatus(bedQuery);
            }

            Long bedId = oldManSupplement.getBedId();
            if(bedId != null || !bedId.equals(0)){
//                OmcOldmanExpenseItem delete = new OmcOldmanExpenseItem();
//                delete.setOldmanId(oldmanId);
//                omcOldmanExpenseItemService.delete(delete);
//
//                OmcOldManSupplement omcOldManSupplement = new OmcOldManSupplement();
//                omcOldManSupplement.setOldManId(oldmanId);
//                omcOldManSupplement = omcOldManSupplementService.selectOne(omcOldManSupplement);
//                omcOldManSupplement.setIsPayed(0);
//                omcOldManSupplementService.update(omcOldManSupplement);
//
//                Oldman oldman = new Oldman();
//                oldman.setOldmanId(oldmanId.intValue());
//                oldman = oldmanService.selectByOld(oldman);
//                oldman.setStatus(11);
//
////                throw new OmcBizException(ErrorCodeEnum.OMC10037038);
//                return WrapMapper.ok(0);
                Bed bedCheck = bedService.selectById(bedId.intValue());

                if(bedCheck != null){
                    //校验床位状态
//                    if(bedCheck.getStatus().equals(0) || bedCheck.getStatus().equals(3)){
                        //如果床位状态为咨询预约，查询是否是同一人
                        if(bedCheck.getStatus().equals(3)){

                            //设置咨询记录id
                            Long bedAdvisoryId = null;
                            OmcOldManSupplement osQuery = new OmcOldManSupplement();
                            osQuery.setOldManId(oldmanId);
                            osQuery = omcOldManSupplementService.selectOne(osQuery);
                            if(osQuery.getAdvisoryId() != null){
                                OmcAdvisory advisoryQuery = omcAdvisoryService.selectByKey(osQuery.getAdvisoryId());
                                if(advisoryQuery != null && advisoryQuery.getBedId() != null){
                                    Bed bedAdvisory = bedService.selectById(advisoryQuery.getBedId().intValue());
                                    if(bedAdvisory.getBedId() != null){
                                        bedAdvisoryId = bedAdvisory.getBedId().longValue();
                                    }
                                }
                            }
                            if(bedAdvisoryId == null || !bedAdvisoryId.equals(bedId)){
                                throw new OmcBizException(ErrorCodeEnum.OMC10034009);
                            }
                        }
//                    }else {
//                        throw new OmcBizException(ErrorCodeEnum.OMC10034006);
//                    }

                    //(1)修改床位状态 床位状态 0-空床 1-暂出 2-有人  3-咨询入住时的预约 4-入住时的预约 5 - 试入住 6-调房预约 7-待缴费
                    bedCheck.setStatus(2);
                    bedCheck.setOldmanId(oldmanId.intValue());
                    int bedRet = bedService.updateById(bedCheck);
                }
            }*/

            //(2)存入老人入院日期、预缴周期id
            oldManSupplement.setInDate(oldmanIeType.getInDate());
            oldManSupplement.setPrepaidCycleId(omcPrepaidCycle.getId());
            oldManSupplement.setUpdateInfo(loginAuthDto);
            int dateRet = omcOldManSupplementService.update(oldManSupplement);

        }else{
            throw new OmcBizException(ErrorCodeEnum.OMC10038002);
        }

        //7.将余额存入cn_omc_old_man_account_funds表中
        OmcOldManAccountFunds oaf = new OmcOldManAccountFunds();
        oaf.setOldManId(oldmanId);
        omcOldManAccountFundsService.delete(oaf);
        //修改余额
        oaf.setGroupId(loginAuthDto.getGroupId());
        oaf.setActPaidFee(inActualFee);
        oaf.setRemainder(totalPrepaidFee.subtract(surplusCycleFee.multiply(prepaidSurplus)));
        int updateAccountFunds = omcOldManAccountFundsService.save(oaf);

        return WrapMapper.ok(updateAccountFunds);
    }


}
